package com.ruoyi.project.yingyu.withdraw.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OrderUtil;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.yingyu.transferorder.domain.TransferOrder;
import com.ruoyi.project.yingyu.transferorder.service.ITransferOrderService;
import com.ruoyi.project.yingyu.withdraw.service.WeixinService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.api.PayMchAPI;
import weixin.popular.bean.paymch.SecapiPayRefund;
import weixin.popular.bean.paymch.SecapiPayRefundResult;
import weixin.popular.bean.paymch.Transfers;
import weixin.popular.bean.paymch.TransfersResult;
import weixin.popular.client.LocalHttpClient;

import java.io.File;
import java.math.BigDecimal;
import java.util.UUID;

@Service
public class WeixinServiceImpl implements WeixinService {

    public static final Logger log = LoggerFactory.getLogger(WeixinServiceImpl.class);

    /*public static String WX_PAY_APP_ID = "wxc82b8a2796d988f8";

    public static String WX_PAY_MCHID = "1534312541";

    public static String WX_PAY_MCH_KEY = "58fbb3abc8ca2e6a1649b80293a26a77";

    public static String KEY_STORE_FILE_PATH = "/data/wwwdata/kkconsole/IYVIMW9uhRdupBbj.p12";*/
    // public static String KEY_STORE_FILE_PATH =
    // "/Users/jackyshi/Documents/apiclient_cert.p12";

    public static String WX_PAY_APP_ID = "wx8cdbec9d13397359";

    public static String WX_PAY_MCHID = "1587792211";

    public static String WX_PAY_MCH_KEY = "7b66d67e039f441f91f27e71957e4111";

    public static String KEY_STORE_FILE_PATH = "/data/wwwdata/kkconsole/IYVIMW9uhRdupBbj.p12";

    static {
        File file = new File(KEY_STORE_FILE_PATH);
        if (file.exists()) {
            LocalHttpClient.initMchKeyStore(WX_PAY_MCHID, KEY_STORE_FILE_PATH);
        } else {
            log.warn("key file not exists[{}]", KEY_STORE_FILE_PATH);
        }
    }

    @Autowired
    ITransferOrderService transferOrderService;

    public boolean refund(String payOrderNo, String orderNo, int totalFee, String refundDesc, String refundNotifyUrl) {

        SecapiPayRefund secapiPayRefund = new SecapiPayRefund();
        secapiPayRefund.setTransaction_id(payOrderNo);
        secapiPayRefund.setMch_id(WX_PAY_MCHID);
        secapiPayRefund.setOut_refund_no(orderNo);
        secapiPayRefund.setNotify_url(refundNotifyUrl);
        secapiPayRefund.setRefund_desc(refundDesc);
        secapiPayRefund.setOrder_amount(new BigDecimal(totalFee));
        secapiPayRefund.setRefund_fee(totalFee);
        secapiPayRefund.setRefund_fee_type("CNY");
        SecapiPayRefundResult result = PayMchAPI.secapiPayRefund(secapiPayRefund, WX_PAY_MCH_KEY);

        if (StringUtils.equals("SUCCESS", result.getResult_code()) && StringUtils.equals("SUCCESS", result.getResult_code())) {
            return true;
        }

        return false;
    }

    @Override
    @Transactional
    public boolean transfer(long kkid, String openid, int fee, String ip, String nickname) {

        String orderNo = OrderUtil.genOrderNo();
        String nonceStr = UUID.randomUUID().toString().replace("-", "");

        Transfers transfers = new Transfers();

        transfers.setAmount(fee);
        transfers.setOpenid(openid);
        transfers.setMch_appid(WX_PAY_APP_ID);
        transfers.setMchid(WX_PAY_MCHID);
        transfers.setCheck_name("NO_CHECK");
        transfers.setDesc("记背单词提现到帐");
        transfers.setNonce_str(nonceStr);
        transfers.setPartner_trade_no(orderNo);
        transfers.setSpbill_create_ip(ip);

        TransfersResult transfersResult = PayMchAPI.mmpaymkttransfersPromotionTransfers(transfers, WX_PAY_MCH_KEY);

        log.info("transfer.openid[{}], fee[{}], ip[{}], kkid[{}], return_code[{}], result_code[{}], error_code[{}], error_code_des[{}]", openid, fee, ip, kkid, transfersResult.getReturn_code(),
                transfersResult.getResult_code(), transfersResult.getErr_code(), transfersResult.getErr_code_des());

        TransferOrder transferOrder = new TransferOrder();
        transferOrder.setCreateBy(ShiroUtils.getLoginName());
        transferOrder.setCreateTime(DateUtils.getNowDate());
        transferOrder.setErrCode(transfersResult.getErr_code());
        transferOrder.setErrCodeDesc(transfersResult.getErr_code_des());
        transferOrder.setFee(Long.valueOf(fee));
        transferOrder.setIp(ip);
        transferOrder.setNonceStr(nonceStr);
        transferOrder.setKkid(kkid);
        transferOrder.setOpenid(openid);
        transferOrder.setOrderNo(orderNo);
        transferOrder.setPaymentNo(transfersResult.getPayment_no());
        transferOrder.setNickname(nickname);
        if (!StringUtils.isEmpty(transfersResult.getPayment_time())) {
            transferOrder.setPaymentTime(DateUtils.parseDate(transfersResult.getPayment_time()));
        }
        transferOrder.setResultCode(transfersResult.getResult_code());

        transferOrderService.insertTransferOrder(transferOrder);

        if (StringUtils.equals("SUCCESS", transfersResult.getResult_code()) && StringUtils.equals("SUCCESS", transfersResult.getResult_code())) {
            return true;
        }

        return false;
    }

}
